package com.example.vue_shop.components.login.controller;

import com.example.vue_shop.components.login.service.LoginService;
import com.example.vue_shop.components.user.entity.User;
import com.example.vue_shop.utils.JwtUtils;
import com.example.vue_shop.utils.ResultObj;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author lipengwei
 */
@RestController
@Api(tags = "登录")
public class LoginController {

    @Resource(name = "loginServiceImpl")
    private LoginService loginService;

    /**
     * 登录接口.
     *
     * @param user 用户
     * @return ResultObj<User> 封装的返回对象
     */
    @ApiOperation(value = "管理系统登录接口", notes = "用于后台管理系统登录")
    @PostMapping("/login")
    public ResultObj<String> login(@ApiParam(name = "user", value = "用户",
            required = true) @RequestBody User user) {
        ResultObj<String> resultObj = new ResultObj<>();

        User userLogin = loginService.login(user);
        if (userLogin == null) {
            resultObj.setStatus(false);
            resultObj.setMessage("用户名或密码错误");
        } else {
            try {
                String token = JwtUtils.getToken(new HashMap<>(0),
                        userLogin);
                resultObj.setData(token);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            resultObj.setMessage("登录成功");
        }
        return resultObj;
    }
}
